import axios from 'axios'
import { message } from 'antd'
import {createBrowserHistory} from "history"
import store from '../store'
// interface token{
//     token:any
// }
let history = createBrowserHistory()
//实例化aixos
var service = axios.create({
    timeout: 10*1000,
    baseURL: process.env.REACT_APP_BASE_API
})
//设置请求拦截器
service.interceptors.request.use(
    (config)=>{
        //设置请求头参数
        // config.headers['token'] = localStorage.getItem('token');
        config.headers['token'] = store.getState().userInfo.token; 

        return config;
    },
    (error)=>{
        return Promise.reject(error)
    }
)
//设置响应拦截器
service.interceptors.response.use(
    (res)=>{
        if( res.data.code == '10119' ){

            message.error('登陆过期,重新登录!!')

            store.dispatch({ type: 'REMOVE_TOKEN' })
            
            history.push('/login');

            history.go(0);
        }
        return res
    },
    (error)=>{
        if( error.response.status == 401 ){
            message.error('登陆过期,重新登录!!')
            // localStorage.removeItem('token')
            history.push('/login');
            history.go(0);
        }else if( error.response.status == 404 ) {
            message.error('访问路径有误!')
            
        }else if( error.response.status == 500 ) {
            message.error('服务器内部错误!')
            
        }else if( error.response.status == 503 ) {
            message.error('服务器无法提供服务!')
            
        }

        return Promise.reject(error)
    }
)

export default service;
